<style lang="scss">
@import '../static/common/variable.scss';

.mine {
  width: 100%;
  padding: $pad;
  padding-bottom: 90px;

  header {
    .img-box {
      width: 100px;
      height: 100px;
      background-color: #f0f0f0;
      border-radius: 50%;
      position: relative;
      img {
        width: 100px;
        height: 100px;
        border-radius: 50%;
      }
      input[type='file'] {
        display: block;
        width: 100px;
        height: 100px;
        border-radius: 50%;
        opacity: 0;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 10;
      }
    }

    p {
      font-size: 18px;
      padding: 10px 0;

      span {
        color: #666;
      }
    }
  }

  section {
    margin-top: 20px;

    ul {
      a {
        display: flex;
        justify-content: space-between;
        align-items: center;
        text-decoration: none;
        color: #333;
        padding: 15px;
        font-size: 19px;
        border-bottom: 1px solid #f0f0f0;
      }
    }
  }
}
</style>
<template>
  <div class="mine">
    <header>
      <div class="img-box">
        <img v-if="form.user_src" :src="form.user_src" alt="">
        <input type="file" @change="chooseFn(form.user_src)" ref="inp">
      </div>
      <div>
        <p>昵称: <span>{{ form.user_name ? form.user_name : '未设置昵称' }}</span></p>
      </div>
      <div>
        <p>账号: <span>{{ form.user_acc }}</span></p>
      </div>
    </header>

    <section>
      <ul>
        <li>
          <RouterLink to="/collect"><span>我的收藏 </span>
            <RightOutlined style="color: #666;" />
          </RouterLink>
        </li>
        <li>
          <RouterLink to="/sigin"><span>我的签到 </span>
            <RightOutlined style="color: #666;" />
          </RouterLink>
        </li>
        <li>
          <RouterLink to="/manage"><span>个人资料 </span>
            <RightOutlined style="color: #666;" />
          </RouterLink>
        </li>
        <li>
           <a href="javascript:;" @click="showTip"><span>退出登录</span> <RightOutlined style="color: #666;" /></a>
        </li>
      </ul>
    </section>


    <a-modal v-model:visible="visible" title="提示" @ok="handleOk"  ok-text="确认"
      cancel-text="取消">
      <!-- <p>提示</p> -->
      <div>确定退出登录吗?</div>
    </a-modal>


  </div>
</template>

<script  lang="ts">
import { reactive, ref } from 'vue'
import { isLoginFn } from '../api/index';
import { RightOutlined } from '@ant-design/icons-vue';
import { uploadPhotoFn, modifyUserSrcFn, getUserInfoFn , removePhotoFn} from '../api/index';
import { useRouter } from 'vue-router'

export default {
  components: { RightOutlined },//注册图标
  setup() {
    let visible = ref(false)
    let router = useRouter()
    const showTip = () => {
      visible.value = true;
    }
    // 退出登录
    let handleOk = () => {
      localStorage.removeItem('TOKEN')
      localStorage.removeItem('user_name')
      router.push({path: '/'})
    }
    let form = reactive({
      user_acc: '',
      user_src: '',
      user_name: '',
      user_create_time: '',
      file: null
    })

    const getUserInfo = async () => {
      let token = localStorage.getItem('TOKEN');
      await getUserInfoFn({ token })
        .then(
          (content: any) => {
            // console.log(1.0, content)
            let { code, msg, data } = content;
            if (code == 200) {
              // 解构赋值
              let { user_acc, user_create_time, user_src, user_name } = data[0];
              form.user_acc = user_acc;
              form.user_create_time = user_create_time;
              form.user_src = user_src;
              form.user_name = user_name;
            }
            else {
              console.log(msg);
            }
          }
        )
    }

    getUserInfo();


    // 选择图片
    let inp = ref();
    const chooseFn = async (src:string) => {
      let token = localStorage.getItem('TOKEN');
      // 检查数据
      // console.dir(inp.value.files[0]);   
      if (inp.value && inp.value.files[0]) {
        let file = inp.value.files[0];
        form.file = file;
        // 读取图片，在本地预览
        // 1.0 创建读取文件的对象
        const reader = new FileReader();
        // 2.0 加载完成执行的事件
        reader.onload = function (event: any) {
          let photo: any = event.target.result; // 获取文件内容
          // console.log("x.0",photo)// base64格式
          // 上传图片
          let formData = new FormData()
          formData.append('photo', file)
          uploadPhotoFn(formData)
          .then(
             (content:any )=>{
                // console.log('1.0',content)
                let {code, picUrl} = content;
                if(code == 200) {
                    // 设置头像
                    modifyUserSrcFn({token, user_src: picUrl})
                    .then(
                        (res: any)=> {
                            let {code} = res;
                            // console.log('2.0',res)
                            if(code == 200) {
                              // 显示头像
                              form.user_src = picUrl;

                              if(src) {
                                // 删除旧图片
                                removePhotoFn({picUrl: src, dirName: 'upload'})
                                .then(
                                  con=> {
                                    console.log('x.0',con);
                                  }
                                )
                              }
                            }
                        }
                    )
                }
             }
          )
        }
        // 3.0 文件资源
        reader.readAsDataURL(file);
      }
    }



    return {
      form,
      inp,
      visible,
      chooseFn,
      handleOk,
      showTip
    }
  },
  // 组件内的守卫（钩子函数）
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被验证前调用
    // 不能获取组件实例 `this` ！
    // 因为当守卫执行时，组件实例还没被创建！
    // console.log('test',next)
    let token = localStorage.getItem('TOKEN');
    if (token) {
      isLoginFn({ token })
        .then(
          content => {
            // console.log('xx:',content);
            let { code } = content;
            if (code == 200) {
              next()
            }
            else {
              if (confirm('您的登录已过期，请重新登录')) {
                next({ path: '/login' })
              }
              else {
                next(false)
              }
            }
          },
          (err) => {
            //  console.log(err);
            if (confirm('请重新登录.')) {
              next({ path: '/login' })
            }
            else {
              next(false)
            }
          }
        )
    }
    else {
      if (confirm('需要跳转到登录页?')) {
        next({ path: '/login' });
      }
      else {
        next(false);
      }
    }
  },
}
</script>